package com.yhh.yapiclientsdk.client;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.yhh.yapiclientsdk.model.User;
import com.yhh.yapiclientsdk.utils.SignUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author hyh
 * @date 2024/8/6
 * @description 模拟调用第三方接口的客户端
 */
public class YApiClient {

    private static final String GATEWAY_HOST = "http://localhost:8090";

    private String accessKey;
    private String secretKey;

    public YApiClient(String accessKey, String secretKey) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }

    /**
     * 用于构造请求头
     *
     * @return
     */
    private Map<String, String> getHeaderMap(String body) {
        Map<String, String> headers = new HashMap<>();
        headers.put("accessKey", accessKey);
//        headers.put("secretKey", secretKey);//secretKey不能放在请求头中传递
        headers.put("body", body);
        headers.put("nonce", RandomUtil.randomNumbers(4));
        headers.put("timestamp", String.valueOf(System.currentTimeMillis()));
        headers.put("sign", SignUtils.getSign(body, secretKey));
        return headers;
    }


    public String getUserNameByPost(User user) {
        String jsonStr = JSONUtil.toJsonStr(user);
//        String url = "http://localhost:8102/api/name/user/";
        String url = GATEWAY_HOST + "/api/name/user/";
        //链式构建请求
        String json = JSONUtil.toJsonStr(user);
        HttpResponse httpResponse = HttpRequest.post(url)
                .addHeaders(getHeaderMap(jsonStr))
                .body(jsonStr)
                .execute();
        System.out.println(httpResponse.getStatus());
        String result = httpResponse.body();
        System.out.println(result);
        return result;
    }


    public String getNameByGet(String name) {
        //可以单独传入http参数，这样参数会自动做URL编码，拼接在URL中
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", "北京");

        String result = HttpUtil.get(GATEWAY_HOST + "/api/name/get/", paramMap);
        System.out.println(result);
        return result;
    }

    public String getNameByPost(String name) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", "上海");

        String result = HttpUtil.post(GATEWAY_HOST + "/api/name/post/", paramMap);
        System.out.println(result);
        return result;
    }
}
